package com.xiaomili.halfsugar.utils;

import android.content.Context;
import android.os.Handler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by WangQi on 2016/7/14.
 */
public class OkHttpUtil {
    private static OkHttpUtil mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mHandler;

    //=======================================================================
    // 双层验证的单例设计模式
    //=======================================================================
    private OkHttpUtil(Context context) {
        mHandler = new Handler();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        int cacheSize = 10 << 20;
        mOkHttpClient = builder.cache(new Cache(context.getCacheDir(), cacheSize))//设置缓存目录和大小
                .connectTimeout(20, TimeUnit.SECONDS)//连接时间
                .readTimeout(20, TimeUnit.SECONDS)//读取时间
                .writeTimeout(15, TimeUnit.SECONDS)//写入时间
                .build();
    }

    //提供静态方法供外部调用，返回当前类的对象
    public static OkHttpUtil newInstance(Context context) {
        if (mInstance == null) {
            //同步锁，只允许一个执行路径进入
            synchronized (OkHttpUtil.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpUtil(context);
                }
            }
        }
        return mInstance;
    }

    //=======================================================================
    // Get异步请求方式
    //=======================================================================
    public void getAsyncData(String url, final MyCallBack myCallBack) {
        final Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handleFailure(e, myCallBack);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                handleSuccess(result, myCallBack);
            }
        });
    }

    //=======================================================================
    // Post异步请求方式
    //=======================================================================
    public void PostAsyncData(String url, Map<String, String> params, final MyCallBack myCallBack) {
        FormBody.Builder formBody = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formBody.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody requestBody = formBody.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handleFailure(e, myCallBack);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                handleSuccess(result, myCallBack);
            }
        });
    }

    //处理成功的请求
    private void handleSuccess(final String result, final MyCallBack myCallBack) {
        //主线程执行
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                myCallBack.onResponse(result);
            }
        });
    }

    //处理失败的请求
    private void handleFailure(final IOException e, final MyCallBack myCallBack) {
        //主线程中执行
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                myCallBack.onFailure(e);
            }
        });
    }

    //自定义接口，返回请求数据
    public interface MyCallBack {
        void onFailure(IOException e);

        void onResponse(String result);
    }
}
